import Vue from 'vue'
import Router from 'vue-router'
// 导入组件
import Login from '@/components/Login.vue'
import Home from '@/components/Home.vue'
import Welcome from '@/components/Welcome.vue'

// 用户
import Users from '@/components/users/Users.vue'

// 权限
import Rights from '@/components/power/Rights.vue'
import Roles from '@/components/power/Roles.vue'

// 商品管理
import Goods from '@/components/goods/List.vue'
import Params from '@/components/goods/Params.vue'
import Cate from '@/components/goods/Cate.vue'
import Add from '@/components/goods/Add.vue'

// 订单管理
import Order from '@/components/order/Order.vue'

// 数据统计
import Reports from '@/components/report/Report.vue'

Vue.use(Router)

const baseTitle = '后台管理'

const router = new Router({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login, meta: { title: '登录页面' } },
    {
      path: '/home',
      component: Home,
      redirect: '/welcome',
      children: [
        { path: '/welcome', component: Welcome, meta: { title: '欢迎页面' } },
        { path: '/users', component: Users, meta: { title: '用户管理' } },
        { path: '/rights', component: Rights, meta: { title: '权限管理' } },
        { path: '/roles', component: Roles, meta: { title: '角色列表' } },
        { path: '/welcome', component: Welcome },
        { path: '/users', component: Users },
        { path: '/rights', component: Rights },
        { path: '/roles', component: Roles },
        { path: '/goods', component: Goods },
        { path: '/goods/add', component: Add },
        { path: '/params', component: Params },
        { path: '/categories', component: Cate },
        { path: '/orders', component: Order },
        { path: '/reports', component: Reports }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = baseTitle + ' - ' + to.meta.title
  } else {
    document.title = baseTitle
  }
  let token = window.sessionStorage.getItem('token')
  if (to.path === '/login') {
    if (!token) {
      return next()
    }
    next('/home')
  }
  if (!token) {
    return next('/login')
  }
  next()
})

export default router
